#include "reporteditdialog.h"
#include <QVBoxLayout>
#include <QIcon>
#include <QPushButton>
#include <QLabel>
#include "confirmdialog.h"

ReportEditDialog::ReportEditDialog(Action* action, QWidget *parent) :
    QDialog(parent),m_aid(action->id()),m_content(this), m_reports(this)
{
    QVBoxLayout* main = new QVBoxLayout;
    QHBoxLayout* hlay = new QHBoxLayout;
    hlay->addWidget(new QLabel(tr("Отчет об эффективности")));
    hlay->addWidget(&m_reports);
    main->addLayout(hlay);
    main->addWidget(&m_content);
    hlay = new QHBoxLayout;
    main->addLayout(hlay);
    QPushButton* btn = new QPushButton(tr("Отмена"),this);
    connect(btn,SIGNAL(clicked()),this,SLOT(reject()));
    hlay->addStretch();
    hlay->addWidget(btn);
    btn = new QPushButton(tr("Готово"),this);
    connect(btn,SIGNAL(clicked()),this,SLOT(onOkClick()));
    connect(btn,SIGNAL(clicked()),this,SLOT(accept()));
    hlay->addWidget(btn);
    setLayout(main);
    setWindowTitle(tr("Новый отчет об эффективности"));
    setWindowIcon(QIcon(":/report_add"));

    m_db = dynamic_cast<TreeDoc*>(action->treeWidget())->db();
    DbConnection::QueryResult res = m_db->execute(tr("SELECT oms.in_quarter_by_date(c.time_show::date),  "
                                                     "oms.in_quarter_by_date(now()::date) "
                                                     "FROM oms.confirmations c "
                                                     "JOIN oms.events e USING (event) "
                                                     "JOIN oms.ex_messages m ON m.eid=c.eid "
                                                     "WHERE e.eid=%1 "
                                                     "AND e.event_type=22 "
                                                     "ORDER BY c.time_show").arg(action->id()));
    if(res.success())
    {
        if(res.rows()==0)
        {
            QString data="{%1,%2}";
            int qu,mo=QDate::currentDate().month();
            if(mo<4)
                qu=1;
            else
            {
                if(mo<7)
                    qu=2;
                else
                {
                    if(mo<10)
                        qu=3;
                    else
                        qu=4;
                }
            }
            m_reports.addItem(tr("за текущий квартал"),data.arg(qu).arg(QDate::currentDate().year()));
        }
        else
            for(int i=0;i<res.rows();i++)
            {
                if(res.at(i,0).toString()==res.at(i,1).toString())
                    m_reports.addItem(tr("за текущий квартал"),res.at(i,0));
                else
                    m_reports.addItem(reportCaption(res.at(i,0).toString()),res.at(i,0));
            }
    }

}

QString ReportEditDialog::content() const
{
    QString tmp=m_content.document()->toPlainText();
    return tmp;
}

QString ReportEditDialog::reportCaption(const QString&quarter) const
{
    QString caption=tr("за %1 квартал %2 г."),q=quarter;
    QStringList qu = q.replace(QRegExp("[{}]"),"").split(",");
    return caption.arg(qu[0]).arg(qu[1]);
}

void ReportEditDialog::onOkClick()
{
    ConfirmDialog cd(m_db,this);
    if(cd.exec()==QDialog::Accepted)
    {
        DbConnection::QueryResult res
                = m_db->execute(tr("select =schema=.ex_append_report(%1,'%2','%3'::int[])")
                                   .arg(m_aid)
                                   .arg(content())
                                   .arg(m_reports.itemData(m_reports.currentIndex()).toString()));
        if(!res.success())
            QMessageBox::warning(this,tr("Ошибка"),tr("Невозможно построить запрос"));
    }
}
